package com.wyz.saas.common.utils;

import com.vividsolutions.jts.geom.*;

import java.io.*;

public final class GeometryUtils {

    private static final GeometryFactory geometryFactory;

    static {
        geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
    }

    public static GeometryFactory factory() {
        return geometryFactory;
    }

    public static Point createPoint(double x, double y, double z) {
        return geometryFactory.createPoint(new Coordinate(x, y, z));
    }

    public static <T extends Geometry> byte[] geometrySerializerBytes(T geometry) {
        try (
                ByteArrayOutputStream bytea = new ByteArrayOutputStream();
                ObjectOutputStream stream = new ObjectOutputStream(bytea);
        ) {
            stream.writeObject(geometry);
            stream.flush();
            return bytea.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T extends Geometry> T geometryDeserializerBytes(Class<T> geometry, byte[] bytes) {
        try (
                ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes))
        ) {
            Object tempGeometry = objectInputStream.readObject();
            if (tempGeometry instanceof Geometry) {
                return (T) tempGeometry;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T extends Geometry> String geometrySerializerJson(T geometry) {
        try {
            return JacksonUtils.objectMapper().writeValueAsString(geometry);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T extends Geometry> T geometryDeserializerJson(Class<T> geometryClass, String json) {
        try {
            return JacksonUtils.objectMapper().readValue(json, geometryClass);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
